package com.lintf.distributed.transaction.inventory.exception;

import com.sun.mail.iap.ConnectionException;
import org.springframework.dao.TransientDataAccessException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeoutException;

@Service
public class ErrorClassifier {

    private final List<Class<? extends Exception>> transientErrors = Arrays.asList(
            TimeoutException.class,
            ConnectionException.class,
            TransientDataAccessException.class
    );

    public ErrorType classifyError(Exception ex) {
        // 1. 检查异常继承链
        Throwable cause = ex.getCause();
        while (cause != null) {
            if (isTransient(cause.getClass())) {
                return ErrorType.TRANSIENT;
            }
            cause = cause.getCause();
        }

        // 2. 匹配异常类型
        if (isTransient(ex.getClass())) {
            return ErrorType.TRANSIENT;
        }

        // 3. 默认不可恢复
        return ErrorType.PERSISTENT;
    }

    private boolean isTransient(Class<?> exceptionClass) {
        return transientErrors.stream()
                .anyMatch(clazz -> clazz.isAssignableFrom(exceptionClass));
    }
}